package ernie.server;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Filip Lindqvist <buggfille@gmail.com>
 * @created 2:40:55 PM - Nov 16, 2011
 */
public class ParameterParser {

    private final String query;

    public ParameterParser(URI u) {
        query = u.getRawQuery();
    }

    @SuppressWarnings("unchecked")
    public Map<String, String> parseQuery() throws UnsupportedEncodingException {
        Map<String, String> parameters = new HashMap<String, String>();
        if (query != null) {
            String pairs[] = query.split("[&]");

            for (String pair : pairs) {
                String param[] = pair.split("[=]");

                String key = null;
                String value = null;
                if (param.length > 0) {
                    key = URLDecoder.decode(param[0],
                            System.getProperty("file.encoding"));
                }
                if (param.length > 1) {
                    value = URLDecoder.decode(param[1],
                            System.getProperty("file.encoding"));
                }
                parameters.put(key, value);
            }
        }
        return parameters;
    }
}